<?php

class Am_Grid_Filter_Job extends Am_Grid_Filter_Abstract
{
    protected $title;
    public function __construct()
    {
        $this->title = ___("Filter By Url");
        parent::__construct();
    }
    public function getVariablesList()
    {
        $ret = parent::getVariablesList();
        $ret[] = 'search';
        $ret[] = 'search_load';
        return $ret;
    }
    protected function applyFilter()
    {
        // done in initFilter
    }
  
   
    public function renderInputs()
    {
        return $this->renderInputText('filter');
    }
    public function initFilter(Am_Grid_ReadOnly $grid)
    {
        parent::initFilter($grid);
        $query = $grid->getDataSource();
       // $query->setPrefix('_u_search');
        /* @var $query Am_Query_User */
        if ($id = $grid->getRequest()->getInt('search_load')){
            $query->load($id);
        } elseif (is_string($this->vars['filter']) && $this->vars['filter']){
            $cond = new Am_Query_Job_Condition_Filter();
			
            $cond->setFromRequest(array('filter' => array('val' => $this->vars['filter'])));
            $query->add($cond);
        } else {
            $query->setFromRequest($grid->getCompleteRequest());
        }
    }
    public function isFiltered()
    {
        return (bool)$this->grid->getDataSource()->getConditions();
    }
}

class AdminJobsController extends Am_Controller_Grid
{
    public function preDispatch()
    {
        parent::preDispatch();
      
    }
   
    
    public function checkAdminPermissions(Admin $admin)
    {
        return $admin->hasPermission('grid_u');
    }
    
    public function createGrid()
    {
       	//$ds = new Am_Query($this->getDi()->jobTable);
		$ds = new Am_Query_Job;
		$ds->addField('(SELECT count(a.id) FROM ?_auto_vote a WHERE a.job_id_server = j.job_id_server)',  'reports_count');
		$ds->addField('(SELECT login FROM ?_user u WHERE u.user_id = j.user_id)', 'username');
		$ds->setOrder('job_id_server');
      //  $ds->setOrderRaw("0+IFNULL(sort_order,0),title");
      /*  $ds->addField("concat(name_f, ' ', name_l)", 'name')
          ->addField('(SELECT count(p.invoice_payment_id) FROM ?_invoice_payment p WHERE p.user_id = u.user_id)',  'payments_count')
          ->addField('IFNULL((SELECT sum(p.amount) FROM ?_invoice_payment p WHERE p.user_id = u.user_id),0)-' .
                     'IFNULL((SELECT sum(r.amount) FROM ?_invoice_refund r WHERE u.user_id=r.user_id),0)',  
              'payments_sum');*/
        //$ds->setOrder("login");
        $grid = new Am_Grid_Editable('_j', ___("Browse Jobs"), $ds, $this->_request, $this->view);
		$grid->setRecordTitle(___('Job'));
		$grid->addGridField(new Am_Grid_Field('job_id', 'ID', true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('job_id_server', ___('IDServer'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('user_id', ___('User ID'), true, '', null, '5%'));
		
		$grid->addGridField(new Am_Grid_Field('url', ___('Url'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('title', ___('Title'), true, '', null, '5%'));
		
		$grid->addGridField(new Am_Grid_Field('tags', ___('Tags'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('description', ___('Description'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('decaptcher', ___('Decaptcher'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('priority', ___('Priority'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('vote', ___('Vote'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('main_success', ___('Main success'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('username', ___('User Name'), true, '', null, '5%'));
	
		 
	//	$grid->setForm(array($this, 'createForm'));
		 $grid->actionGet('insert')->setTarget('_top')->showFormAfterSave(true);
		$grid->actionAdd($this->createActionExport());
		
		$grid->actionAdd($this->createActionCustomize());	
		

	
		
		
		$actTest = new Am_Grid_Action_Url('reports', ___('View Report this Job'), '__ROOT__/adminjobsreport?jobid=__ID__', '_dreport');
		
		
		
		$grid->actionAdd($actTest);
		
		$actDownload = new Am_Grid_Action_Url('download', ___('Download Report this Job'), '__ROOT__/download?jobid=__ID__&isuser=0', '_dreport');
	
		$grid->actionAdd($actDownload);
		$grid->actionDelete('insert');
		$grid->actionDelete('edit');
		$grid->actionDelete('delete');
	//	$grid->actionAdd(new Am_Grid_Action_DownloadReport());
		$grid->setFilter(new Am_Grid_Filter_Job());
		
    	/* $grid->addField(new Am_Grid_Field('name', ___('Name'), true));
		  $grid->addField(new Am_Grid_Field('email', ___('E-Mail Address'), true));
		   $grid->addField(new Am_Grid_Field('payments_sum', ___('Payments'), true, null, null));*/
        return $grid;
    }
	function createForm()
    {
        return new Am_Form_Admin_Job($this->grid->getRecord());
    }
	protected function createActionCustomize() {
        $action = new Am_Grid_Action_Customize();
		$action->setUser(false);
        $action->addField(new Am_Grid_Field('job_id', ___('Job Id')))
			->addField(new Am_Grid_Field('job_id_server', ___('Job Id Server')))
			->addField(new Am_Grid_Field('user_id', ___('User_Id')))
            ->addField(new Am_Grid_Field('url', ___('Url')))
			->addField(new Am_Grid_Field('title', ___('Title')))
            ->addField(new Am_Grid_Field('tags', ___('Tags')))
			->addField(new Am_Grid_Field('reports_count', ___('Reports')))
			->addField(new Am_Grid_Field('description', ___('Description')))
			->addField(new Am_Grid_Field('decaptcher', ___('Decaptcher')))
			->addField(new Am_Grid_Field('priority', ___('Priority')))
			->addField(new Am_Grid_Field('main_success', ___('Main success')))
			->addField(new Am_Grid_Field('username', ___('User Name')))
			->addField(new Am_Grid_Field('vote', ___('Vote')));
          
			
        
            //Additional Fields
        foreach ($this->getDi()->jobTable->customFields()->getAll() as $field) {
            if (isset($field->from_config) && $field->from_config) {
                if ($field->sql) {
                    $action->addField(new Am_Grid_Field($field->name, $field->title));
                } else {
                    $action->addField(new Am_Grid_Field_Data($field->name, $field->title));
                }
            }
        }

        return $action;
    }
	 protected function createActionExport() {
        $action = new Am_Grid_Action_Export();
		$action->setJobId(0);
		$action->setUser(false);
        $action->addField(new Am_Grid_Field('job_id', ___('Job Id')))
		 	->addField(new Am_Grid_Field('job_id_server', ___('Job Id Server')))
			->addField(new Am_Grid_Field('user_id', ___('User_Id')))
            ->addField(new Am_Grid_Field('url', ___('Url')))
			->addField(new Am_Grid_Field('title', ___('Title')))
            ->addField(new Am_Grid_Field('tags', ___('Tags')))
			->addField(new Am_Grid_Field('description', ___('Description')));
        
        //Additional Fields
        foreach ($this->getDi()->jobTable->customFields()->getAll() as $field) {
            if (isset($field->from_config) && $field->from_config) {
                if ($field->sql) {
                    $action->addField(new Am_Grid_Field($field->name, $field->title));
                } else {
                    //we use trailing __ to distinguish fields from data table
                    $action->addField(new Am_Grid_Field($field->name . '__', $field->title));
                }
            }
        }
        
      //  $action->setGetDataSourceFunc(array($this, 'getDS'));
        return $action;
    }
    
}
